/*
 * Rotate writed by instaruction from
 * http://blog.wolfire.com/2010/07/Linear-algebra-for-game-developers-part-4
 * 
 * writed by Alexey Matveev (AlMat26)
*/

#include <mesh/mesh.h>

void Mesh::computeCollisionRadius () {
    
    collisionRadius = 0;
    
    for ( int i = 0; i < points.size (); i++ ) {
        
        if ( points[i].x > 0 ) {
            
            if ( points[i].x > collisionRadius ) {
                
                collisionRadius = points[i].x;
            }
        } else {
            
            if ( -points[i].x > collisionRadius ) {
                
                collisionRadius = ( -points[i].x );
            }
        }
    }
}

void Mesh::computeCenterPointLocation () {

    double XSum = 0;
    double YSum = 0;
    double ZSum = 0;

    for ( int i = 0; i < viewPoints.size(); i++ ) {

        XSum += viewPoints [i].x;
        YSum += viewPoints [i].y;
        ZSum += viewPoints [i].z;
    }

    centerPoint.x = XSum / viewPoints.size ();
    centerPoint.y = YSum / viewPoints.size ();
    centerPoint.z = ZSum / viewPoints.size ();
}

void Mesh::rotate( double deg, Axis axis ) {
    
    for ( unsigned int i = 0; i < points.size (); i++ ) {
        
        if ( axis == aX ) {
            
            viewPoints[i].y = centerPoint.y + (points[i].y - centerPoint.y)*cos(deg)-(points[i].z-centerPoint.z)*sin(deg);
            viewPoints[i].z = centerPoint.z + (points[i].z - centerPoint.z)*cos(deg)+(points[i].y-centerPoint.y)*sin(deg);
            
        } else if ( axis == aY ) {
            
            viewPoints[i].x = centerPoint.x + (points[i].x - centerPoint.x)*cos(deg)-(points[i].z-centerPoint.z)*sin(deg);
            viewPoints[i].z = centerPoint.z + (points[i].z - centerPoint.z)*cos(deg)+(points[i].x-centerPoint.x)*sin(deg);
            
        } else if ( axis == aZ ) {

            viewPoints[i].x = centerPoint.x + (points[i].x - centerPoint.x)*cos(deg)-(points[i].y-centerPoint.y)*sin(deg);
            viewPoints[i].y = centerPoint.y + (points[i].y - centerPoint.y)*cos(deg)+(points[i].x-centerPoint.x)*sin(deg);
            
        }
    }
}
